package com.ruoyi.labdata.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.labdata.domain.LabOrgnization;
import com.ruoyi.labdata.domain.LabOrgnizationSecond;
import com.ruoyi.labdata.service.ILabOrgnizationSecondService;
import com.ruoyi.labdata.service.ILabOrgnizationService;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 机构Controller
 * 
 * @author winner pan
 * @date 2022-02-02
 */
@RestController
@RequestMapping("/labdata/orgnization")
public class LabOrgnizationController extends BaseController {
	@Autowired
	private ILabOrgnizationService labOrgnizationService;
	@Autowired
	private ISysDeptService sysDeptService;

	@Autowired
	private ILabOrgnizationSecondService labOrgnizationSecondService;

	/**
	 * 查询机构列表
	 * 公共查询  不设置访问权限
	 */
	//@PreAuthorize("@ss.hasPermi('labdata:orgnization:query')")
	@GetMapping("/list")
	public TableDataInfo list(LabOrgnization labOrgnization) {
		startPage();
		List<LabOrgnization> list = labOrgnizationService.selectLabOrgnizationList(labOrgnization);
		return getDataTable(list);
	}

	@GetMapping("/getCheckedList")
	public AjaxResult getCheckedList(LabOrgnization labOrgnization) {
		List<LabOrgnization> list = labOrgnizationService.chooseOrgsQuery(labOrgnization);
		return AjaxResult.success(list);
	}

	/**
	 * 查询直属下级机构列表
	 */
	@PreAuthorize("@ss.hasPermi('labdata:suborg:query')")
	@GetMapping("/sublist")
	public TableDataInfo sublist(LabOrgnization labOrgnization) {
		startPage();
		List<LabOrgnizationSecond> list = labOrgnizationSecondService
				.getDirectSubordinateStatistics(labOrgnization.getOrgId());
		return getDataTable(list);
	}
	
	/**
	 * 查询平台直属下级机构列表
	 */
	@PreAuthorize("@ss.hasPermi('labdata:suborg:query')")
	@GetMapping("/platformlist")
	public TableDataInfo platformlist(LabOrgnization labOrgnization) {
		startPage();
		List<LabOrgnizationSecond> list = labOrgnizationSecondService
				.getPlatformSubordinateStatistics(labOrgnization.getOrgId());
		return getDataTable(list);
	}
	@GetMapping(value = "/orgName/{orgId}")
	public AjaxResult getDeptName(@PathVariable("orgId") Long orgId){
		LabOrgnization labOrgnization = this.labOrgnizationService.selectLabOrgnizationById(orgId);
		if(labOrgnization==null){
			return AjaxResult.success("");
		}
		return AjaxResult.success(labOrgnization.getOrgName());
	}
	
	/**
	 * 查询直属下级机构列表
	 */
	@PreAuthorize("@ss.hasPermi('labdata:suborg:query')")
	@GetMapping("/thirdlist")
	public TableDataInfo thirdlist(LabOrgnization labOrgnization) {
		startPage();
		List<LabOrgnizationSecond> list = labOrgnizationSecondService
				.getThirdSubordinateStatistics(labOrgnization.getOrgId());
		return getDataTable(list);
	}

	/*
	 * 查询直属下级机构列表
	 */
	@PreAuthorize("@ss.hasPermi('labdata:suborg:query')")
	@GetMapping("/rootlist")
	public TableDataInfo rootlist(LabOrgnization labOrgnization) {
		startPage();
		List<LabOrgnizationSecond> list = labOrgnizationSecondService.getUnionStatsticData(labOrgnization.getOrgId());
		return getDataTable(list);
	}

	/**
	 * 导出机构列表
	 */
	//@PreAuthorize("@ss.hasPermi('labdata:orgnization:export')")
	/*@Log(title = "机构", businessType = BusinessType.EXPORT)
	@GetMapping("/export")
	public AjaxResult export(LabOrgnization labOrgnization) {
		List<LabOrgnization> list = labOrgnizationService.selectLabOrgnizationList(labOrgnization);
		ExcelUtil<LabOrgnization> util = new ExcelUtil<LabOrgnization>(LabOrgnization.class);
		return util.exportExcel(list, "orgnization");
	}*/

	/**
	 * 获取机构详细信息
	 */
	@PreAuthorize("@ss.hasPermi('labdata:orgnization:query')")
	@GetMapping(value = "/{orgId}")
	public AjaxResult getInfo(@PathVariable("orgId") Long orgId) {
		LabOrgnization labOrgnization = labOrgnizationService.selectLabOrgnizationById(orgId);
		if (labOrgnization == null) {
			return AjaxResult.error("该机构不存在或已经从组织机构[:labOrgnization]中删除.");
		}
		if(labOrgnization.getOrgGroupOpt()==null){
			labOrgnization.setOrgGroupOpt(Long.valueOf(1));
		}
		if (labOrgnization.getParentId() == 0) {
			labOrgnization.setParentId(null);
		}
		return AjaxResult.success(labOrgnization);
	}

	/**
	 * 获取机构详细信息
	 */
	@GetMapping(value = "/listSecondOrgLab/{orgId}")
	public AjaxResult listSecondOrgLab(@PathVariable("orgId") Long orgId) {
		List<LabOrgnization> labOrgnizationList = labOrgnizationService.listLabBySecondOrgId(orgId);
		return AjaxResult.success(labOrgnizationList);
	}

	/**
	 * 获取机构详细信息
	 */
	@GetMapping(value = "/listOrgByFuntionOpt/{functionOpt}")
	public AjaxResult getThirdLabInfo(@PathVariable("functionOpt") Long functionOpt) {
		List<LabOrgnization> labOrgnizationList = labOrgnizationService.getOrgByFunctionOpt(functionOpt);
		return AjaxResult.success(labOrgnizationList);
	}

	/**
	 * 获取机构详细信息
	 */
	@GetMapping(value = "/searchOrg/{orgName}")
	public AjaxResult searchOrgInfo(@PathVariable("orgName") String orgName) {
		List<LabOrgnization> labOrgnizationList = labOrgnizationService.queryLabOrgnizationByName(orgName);
		return AjaxResult.success(labOrgnizationList);
	}

	/**
	 * 新增机构
	 */
	@PreAuthorize("@ss.hasPermi('labdata:orgnization:edit')")
	@Log(title = "机构", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody LabOrgnization labOrgnization) {
		return toAjax(labOrgnizationService.insertLabOrgnization(labOrgnization));
	}

	/**
	 * 修改机构
	 */
	@PreAuthorize("@ss.hasPermi('labdata:orgnization:edit')")
	@Log(title = "机构", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody LabOrgnization labOrgnization) {
		if (labOrgnization.getParentId() == null) {
			labOrgnization.setParentId(Long.valueOf(0));
		}
		if(this.sysDeptService.hasChildByDeptId(labOrgnization.getOrgId())){
			SysDept dept = this.sysDeptService.selectDeptById(labOrgnization.getOrgId());
			if(dept.getParentId().longValue()!=labOrgnization.getParentId().longValue()){
				return AjaxResult.error("该机构已经包含下级，不能修改机构的父级节点!");
			}
		}
		return toAjax(labOrgnizationService.updateLabOrgnization(labOrgnization));
	}

	/**
	 * 删除机构
	 */
	@PreAuthorize("@ss.hasPermi('labdata:orgnization:edit')")
	@Log(title = "机构", businessType = BusinessType.DELETE)
	@DeleteMapping("/{orgId}")
	public AjaxResult remove(@PathVariable Long orgId) {
		if(labOrgnizationService.checkOrgUsed(orgId)!=null){
			return AjaxResult.error("该机构已经包含用户、下级、设备、备品、化学品之一或全部，不能被删除!");
		}
		return toAjax(labOrgnizationService.deleteLabOrgnizationById(orgId));
	}

	/**
	 * 获取部门下拉树列表 
	 */
	@GetMapping("/treeselect")
	public AjaxResult treeselect(LabOrgnization labOrgnization) {
		if(labOrgnization.getCheckedOrgIds()!=null){
			String[] orgIdStrArray = labOrgnization.getCheckedList();
			List<SysDept> deptList = sysDeptService.selectSysDeptByIds(orgIdStrArray);
			StringBuffer ancestorsBuffer = new StringBuffer();
			for(SysDept dept : deptList){
				ancestorsBuffer.append(dept.getAncestors());
			}
			labOrgnization.setCheckedOrgIds(ancestorsBuffer.toString());
		}
		List<LabOrgnization> depts = labOrgnizationService.getLabOrgnizationTreeList(labOrgnization);
		if(labOrgnization.getOrgGroupOpt()!=null && labOrgnization.getOrgGroupOpt()==2){
			depts = depts.stream().filter(s -> s.getOrgFunctionOpt()!=null && s.getOrgFunctionOpt()>2).collect(Collectors.toList());
		}
		return AjaxResult.success(labOrgnizationService.buildOrgnizationTreeSelect(depts));
	}
	
	/**
	 * 获取平台下拉树列表
	 */
	@GetMapping("/platformTree")
	public AjaxResult platformTree() {
		List<LabOrgnization> depts = labOrgnizationService.listPlatformOrgTree();
		return AjaxResult.success(labOrgnizationService.buildOrgnizationTreeSelect(depts));
	}

}
